package news.dao;

import java.sql.*;

import news.entity.Users;
import news.utils.DBUtils;

/**
 * 用户类的数据库操作类
 * @author Administrator
 *
 */
public class UsersDAO {
	/**
	 * 验证用户登录
	 * @param uname
	 * @param upwd
	 * @return
	 */
	public Users queryUsersByLogin( String uname, String upwd ) {
		Users user = null;
		String sql = "select userid, userName from userinfo where userName=? and userpwd=?";
		Connection conn = DBUtils.getConn();
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, uname);
			pst.setString(2, upwd);
			ResultSet rs = pst.executeQuery();
			if ( rs.next() ) {
				user = new Users(rs.getInt(1),rs.getString(2),null);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.close(conn, pst);
		}
		return user;
	}

	/**
	 * 查询用户的老密码
	 * @param uid
	 * @return
	 */
	public String queryUsersOldPwd(int uid) {
		String oldpwd = null;
		String sql = "select userpwd from userinfo where userid=?";
		Connection conn = DBUtils.getConn();
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setInt(1, uid);
			ResultSet rs = pst.executeQuery();
			if ( rs.next() ) {
				oldpwd = rs.getString(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return oldpwd;
	}

	/**
	 * 修改用户密码
	 * @param pwd
	 * @param uid
	 * @return
	 */
	public boolean modifyUsersPwdByUserID(String pwd, int uid) {
		boolean flag = false;
		String sql = "update userinfo set userpwd=? where userid=?";
		Connection conn = DBUtils.getConn();
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, pwd);
			pst.setInt(2, uid);
			flag = pst.executeUpdate() > 0 ? true : false;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flag;
	}
}
